<template>
  <div class="smart-course-container">
    <!-- 左侧输入区 -->
    <div class="input-section">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <h3>选课目标设置</h3>
            <el-tag type="info">Step 1/2</el-tag>
          </div>
        </template>

        <el-form label-position="top">
          <el-form-item label="想学习的技能：">
            <el-input
              type="textarea"
              :rows="4"
              v-model="inputSkills"
              placeholder="请输入技能关键词，用逗号分隔"
              clearable
              @input="handleSkillsInput"
            />
            <div class="skill-tags">
              <el-tag v-for="(tag, index) in skillTags" :key="index" class="mx-1" effect="plain" @click="addSkill(tag)">
                {{ tag }}
              </el-tag>
            </div>
          </el-form-item>

          <el-form-item label="目标岗位：">
            <el-select v-model="selectedJob" placeholder="请选择职业方向" filterable clearable>
              <el-option v-for="job in jobOptions" :key="job.value" :label="job.label" :value="job.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="推荐倾向：">
            <el-slider v-model="recommendBalance" :marks="balanceMarks" show-stops :max="100" range />
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 中部推荐区 -->
    <div class="recommend-section">
      <el-card shadow="never">
        <template #header>
          <div class="card-header">
            <h3>推荐课程（{{ filteredCourses.length }}）</h3>
            <div class="sort-options">
              <el-radio-group v-model="sortType" size="small">
                <el-radio-button label="match">匹配度</el-radio-button>
                <el-radio-button label="credit">学分</el-radio-button>
                <el-radio-button label="popular">热度</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </template>

        <div v-loading="loading" class="course-list">
          <el-card
            v-for="course in filteredCourses"
            :key="course.id"
            shadow="hover"
            class="course-card"
            :class="{ 'conflict-card': course.conflict }"
          >
            <template #header>
              <div class="course-header">
                <el-tag :type="getCourseTypeTag(course.type)">{{ course.type }}</el-tag>
                <el-rate
                  v-model="course.matchRate"
                  disabled
                  :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                  disabled-void-color="#EFF2F7"
                  :max="5"
                />
              </div>
            </template>

            <div class="course-content">
              <h4 class="course-title">{{ course.name }}</h4>
              <div class="course-meta">
                <span><i class="el-icon-user"></i> {{ course.teacher }}</span>
                <span><i class="el-icon-time"></i> {{ course.time }}</span>
                <span><i class="el-icon-collection"></i> {{ course.credit }}学分</span>
              </div>

              <el-progress :percentage="course.skillCoverage" :color="customProgressColor" :show-text="false" />

              <div class="course-skills">
                <el-tag
                  v-for="(skill, index) in course.relatedSkills"
                  :key="index"
                  size="small"
                  type="info"
                  effect="plain"
                >
                  {{ skill }}
                </el-tag>
              </div>
            </div>

            <template #footer>
              <div class="course-footer">
                <el-button type="primary" size="small" :disabled="course.conflict" @click="toggleCourse(course)">
                  {{ selectedCourses.has(course.id) ? "已选" : "加入课表" }}
                </el-button>
                <el-button size="small" @click="showDetail(course)"> 详情 </el-button>
              </div>
            </template>
          </el-card>
        </div>
      </el-card>
    </div>

    <!-- 右侧详情区 -->
    <div class="detail-section">
      <el-card shadow="hover" v-if="currentCourse">
        <template #header>
          <div class="card-header">
            <h3>课程详情</h3>
            <el-button type="text" @click="currentCourse = null">
              <i class="el-icon-close"></i>
            </el-button>
          </div>
        </template>

        <div class="course-detail">
          <h4 class="detail-title">{{ currentCourse.name }}</h4>
          <el-divider />

          <div class="skill-match">
            <h5>技能匹配度</h5>
            <div class="skill-progress">
              <div v-for="skill in inputSkillList" :key="skill" class="skill-item">
                <span class="skill-label">{{ skill }}</span>
                <el-progress :percentage="getSkillMatchPercent(skill)" :color="skillProgressColor" />
              </div>
            </div>
          </div>

          <el-divider />

          <div class="course-stat">
            <h5>课程数据</h5>
            <div class="stat-grid">
              <div class="stat-item">
                <div class="stat-value">{{ currentCourse.popularity }}%</div>
                <div class="stat-label">选修比例</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ currentCourse.avgScore }}</div>
                <div class="stat-label">平均成绩</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ currentCourse.remaining }}</div>
                <div class="stat-label">剩余名额</div>
              </div>
            </div>
          </div>

          <el-divider />

          <div class="time-slots">
            <h5>可选时间段</h5>
            <div class="slot-list">
              <el-tag
                v-for="(slot, index) in currentCourse.timeSlots"
                :key="index"
                :type="checkTimeConflict(slot) ? 'danger' : 'success'"
                effect="plain"
                class="slot-tag"
              >
                {{ slot }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
  import { ref, computed, watch } from "vue";
  import { ElMessage } from "element-plus";

  // 模拟数据
  const mockCourses = [
    {
      id: 1,
      name: "Web前端开发技术",
      type: "专业必修",
      credit: 3,
      teacher: "张老师",
      time: "周一 1-2节",
      relatedSkills: ["HTML5", "CSS3", "JavaScript"],
      matchRate: 4.5,
      skillCoverage: 85,
      popularity: 78,
      avgScore: 82.5,
      remaining: 15,
      timeSlots: ["周一 1-2节", "周三 3-4节"]
    }
    // 更多模拟数据...
  ];

  // 响应式状态
  const inputSkills = ref("");
  const selectedJob = ref("");
  const recommendBalance = ref(50);
  const sortType = ref("match");
  const loading = ref(false);
  const currentCourse = ref(null);
  const selectedCourses = ref(new Set());

  // 常量数据
  const jobOptions = [
    { label: "前端开发", value: "frontend" },
    { label: "数据分析师", value: "data-analyst" },
    { label: "产品经理", value: "pm" }
  ];

  const skillTags = ["Python", "Java", "数据分析", "机器学习", "UI设计", "项目管理"];

  // 计算属性
  const inputSkillList = computed(() => {
    return inputSkills.value
      .split(",")
      .filter(s => s.trim())
      .map(s => s.trim());
  });

  const filteredCourses = computed(() => {
    return mockCourses
      .filter(course => {
        const matchSkills = inputSkillList.value.some(skill => course.relatedSkills.includes(skill));
        return matchSkills;
      })
      .sort((a, b) => {
        if (sortType.value === "credit") return b.credit - a.credit;
        if (sortType.value === "popular") return b.popularity - a.popularity;
        return b.matchRate - a.matchRate;
      })
      .map(course => ({
        ...course,
        conflict: checkTimeConflict(course.time)
      }));
  });

  // 方法
  const handleSkillsInput = () => {
    // 实际应添加防抖和API调用
    loading.value = true;
    setTimeout(() => (loading.value = false), 500);
  };

  const addSkill = skill => {
    const skills = inputSkillList.value;
    if (!skills.includes(skill)) {
      inputSkills.value = skills.concat(skill).join(", ");
    }
  };

  const toggleCourse = course => {
    if (selectedCourses.value.has(course.id)) {
      selectedCourses.value.delete(course.id);
    } else {
      if (checkTimeConflict(course.time)) {
        ElMessage.warning("时间冲突，请调整后再选");
        return;
      }
      selectedCourses.value.add(course.id);
    }
  };

  const showDetail = course => {
    currentCourse.value = course;
  };

  const checkTimeConflict = time => {
    // 简化的冲突检测逻辑
    return selectedCourses.value.size >= 3; // 示例逻辑
  };

  const getCourseTypeTag = type => {
    const typeMap = {
      专业必修: "success",
      专业选修: "warning",
      公共选修: "info"
    };
    return typeMap[type] || "info";
  };

  const customProgressColor = percentage => {
    return percentage > 80 ? "#67C23A" : percentage > 50 ? "#E6A23C" : "#F56C6C";
  };

  const getSkillMatchPercent = skill => {
    return currentCourse.value?.relatedSkills.includes(skill) ? 100 : 0;
  };

  // 监听器
  watch(inputSkillList, newVal => {
    if (newVal.length > 5) {
      ElMessage.warning("最多输入5个技能关键词");
      inputSkills.value = newVal.slice(0, 5).join(", ");
    }
  });
</script>

<style lang="scss" scoped>
  .smart-course-container {
    display: grid;
    grid-template-columns: 300px 1fr 350px;
    gap: 16px;
    height: 100vh;
    padding: 20px;
    background-color: #f5f7fa;

    .input-section {
      height: calc(100vh - 40px);
      overflow-y: auto;
    }

    .recommend-section {
      height: calc(100vh - 40px);
      overflow-y: auto;

      .course-list {
        display: grid;
        gap: 12px;
        grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      }

      .course-card {
        margin-bottom: 12px;
        transition: transform 0.3s;

        &:hover {
          transform: translateY(-3px);
        }

        &.conflict-card {
          border-left: 4px solid #f56c6c;
        }
      }

      .course-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .course-content {
        .course-title {
          margin: 0 0 8px;
          font-size: 16px;
        }

        .course-meta {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          color: #909399;
          font-size: 12px;
          margin-bottom: 12px;
        }

        .course-skills {
          margin-top: 12px;
          display: flex;
          flex-wrap: wrap;
          gap: 4px;
        }
      }
    }

    .detail-section {
      height: calc(100vh - 40px);
      overflow-y: auto;

      .course-detail {
        .detail-title {
          margin: 0;
          font-size: 18px;
        }

        .skill-match {
          .skill-item {
            margin: 12px 0;

            .skill-label {
              display: block;
              margin-bottom: 4px;
              font-size: 14px;
            }
          }
        }

        .stat-grid {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 16px;

          .stat-item {
            text-align: center;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 4px;

            .stat-value {
              font-size: 18px;
              font-weight: bold;
            }

            .stat-label {
              color: #909399;
              font-size: 12px;
            }
          }
        }

        .time-slots {
          .slot-tag {
            margin: 4px;
            cursor: pointer;
          }
        }
      }
    }
  }

  .skill-tags {
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 4px;

    .el-tag {
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        transform: scale(1.05);
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>
